const { createConnection } = require("typeorm");
const fs = require("fs");
async function loadOrm(app) {
  //加载数据库
  if (app.config.typeorm) {
    const config = app.config.typeorm;
    const filePath = __dirname + "/../../../../entity";
    config.entities = [];
    const entityClassName = [];
    //加载文件
    const fileExists = fs.existsSync(filePath);
    if (fileExists) {
      require("young-require-all")({
        dirname: filePath,
        filter: /(.+)\.ts$/,
        resolve: function (Service) {
          for (let ServiceName in Service) {
            config.entities.push(Service[ServiceName]);
            entityClassName.push(Service[ServiceName].name);
          }
        },
      });
    }
    const connection = createConnection(config)
      .then((connection) => {
        entityClassName.forEach((e) => {
          if (connection[e]) throw new Error(`entity class name repeat:${e}!`);
          connection[e] = connection.getRepository(e);
          app.log.info(
            `entity [${e}] loaded successfully, usage: this.app.orm.${e}`,
            true
          );
        });
        return connection;
      })
      .catch((err) => {
        app.log.error("mysql connect failed: " + err);
      });
    app.orm = await connection;
  } else {
    app.log.warn("config[typeorm] undefined, database uninitialized!", true);
  }
}
module.exports = { loadOrm };
